package org.springblade.modules.evaluate.timing;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.evaluate.dto.StoreScore;
import org.springblade.modules.evaluate.entity.Evaluate;
import org.springblade.modules.evaluate.service.IEvaluateService;
import org.springblade.modules.store.entity.Store;
import org.springblade.modules.store.service.IStoreService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@AllArgsConstructor
public class EvaluateTiming {

    private final IEvaluateService evaluateService;
    private final IStoreService storeService;

    @Scheduled(cron = "0 0 0 * * ? ")
    public void evaluate(){
        List<Evaluate> list = evaluateService.list();
        List<StoreScore> scoreList = new ArrayList<>();
        if (!list.isEmpty()){
        for (Evaluate evaluate : list) {
            boolean flag = false;
            for (StoreScore storeScore : scoreList) {
                if (storeScore.getStoreId().equals(evaluate.getStoreId())){
                    storeScore.setSocre(storeScore.getSocre()+evaluate.getScore());
                    storeScore.setCount(storeScore.getCount()+1);
                    flag = true;
                }
            }
            if (!flag){
                StoreScore storeScore = new StoreScore();
                storeScore.setStoreId(evaluate.getStoreId());
                storeScore.setSocre(evaluate.getScore());
                storeScore.setCount(1d);
                scoreList.add(storeScore);
            }
        }
        scoreList.forEach(storeScore -> {
            Store one = storeService.getOne(Wrappers.<Store>query().lambda()
                    .eq(Store::getLoginId, storeScore.getStoreId()));
            Double score = storeScore.getSocre()/storeScore.getCount();
            one.setScore(Func.toStr(score));
            storeService.updateById(one);
        });
        }
    }
}
